package com.stox.manager;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;

import com.stox.event.NewCountryEvent;
import com.stox.model.Country;
import com.stox.repository.CountryRepository;

@Component
public class CountryManager implements SmartApplicationListener{

	@Autowired
	private CountryRepository countryRepository;
	
	public int getOrder() {
		return 0;
	}
	
	public void onApplicationEvent(ApplicationEvent event) {
		save((Country)event.getSource());
	}
	
	public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
		return NewCountryEvent.class.isAssignableFrom(eventType);
	}
	
	public boolean supportsSourceType(Class<?> sourceType) {
		return Country.class.isAssignableFrom(sourceType);
	}
	
	public List<Country> findAll(){
		return countryRepository.findAll();
	}
	
	private Country save(Country country){
		country = countryRepository.save(country);
		countryRepository.flush();
		return country;
	}
	
}
